<template>
  <view>
    <nav-bar @on-back="onBack" :page-title="lang.pageName"/>
    <view :class="[locale]">
      <view :class="['padding-30']">

        <!-- TODO 链接接口后发布-->

        <!--        <view class="flex-between">-->
        <!--          <view/>-->
        <!--          <view class="radio-40 padding-14-20 add-printer" hover-class="hover" @click="addPrinterShow = true">-->
        <!--            <view class="flex-center gap-20">-->
        <!--              <u-icon name="plus-circle" size="24" color="#fff"/>-->
        <!--              <view class="common-title">{{ lang.addPrinter }}</view>-->
        <!--            </view>-->
        <!--          </view>-->
        <!--        </view>-->

        <view v-for="(item, index) in printerList" :key="index">
          <view class="card padding-40 text-32 column">
            <!-- 打印机头部-->
            <view class="flex-between margin-bottom" style="align-items: flex-start">
              <view class="center gap-20" style="align-items: flex-start">
                <!-- 照片-->
                <view class="image-box">
                  <image class="radio-20 image" src="/static/icon/store/printer.svg"/>
                </view>
                <!-- 打印机名称和状态-->
                <view class="flex-column gap-20">
                  <view class="text-36" style="line-height: normal;">{{ item.name }}</view>
                  <!-- state-->
                  <view>
                    <view :class="['common-icon-text state-label', !item.online ? 'state-label-offline' : '']"
                          style="display: inline-block">
                      {{ lang.printerStatus[item.online ? 'online' : 'offline'] }}
                    </view>
                  </view>
                </view>
              </view>

              <!-- 编译 icon-->
              <view hover-class="hover" @click="onUpdatePrinterInfo(index)">
                <u-icon name="setting-fill" color="#1073FF" size="54rpx"/>
              </view>
            </view>

            <view class="line"/>

            <!-- 打印机编号和型号-->
            <view class="flex-between padding-tb-14 common-title">
              <view>{{ lang.printerInfo['id'] }}</view>
              <view>{{ item.machine.device_id }}</view>
            </view>
            <view class="flex-between padding-tb-14 common-title">
              <view>{{ lang.printerInfo['model'] }}</view>
              <view>{{ item.drivce_name }}</view>
            </view>

            <view class="flex-between padding-tb-14 common-title">
              <view>{{ lang.printerInfo['location'] }}</view>
              <view class="flex-center gap-20">
                <view class="flex-center">
                  <view>{{ lang.printerInfo['latitude'] }}</view>
                  <view class="color-blue">{{ item.latitude }}</view>
                </view>
                <view class="flex-center">
                  <view>{{ lang.printerInfo['longitude'] }}</view>
                  <view class="color-blue">{{ item.longitude }}</view>
                </view>
              </view>
            </view>

            <view class="line"/>

            <!-- 清空打印任务-->
            <view class="flex-between padding-tb-14 common-title" hover-class="hover"
                  @click="onClearPrinterTask(index)">
              <view>{{ lang.operations['clearTask'] }}</view>
              <view>
                <u-icon :name="arrowIcon" size="18"/>
              </view>
            </view>

            <view class="line"/>

            <!-- 重启设备-->
            <view class="flex-between padding-tb-14 common-title" hover-class="hover" @click="onRebootDevice(index)">
              <view>{{ lang.operations['restart'] }}</view>
              <view>
                <u-icon :name="arrowIcon" size="18"/>
              </view>
            </view>

            <!-- TODO 链接接口后发布-->

            <!--            <view class="line"/>-->
            <!--            &lt;!&ndash; 关机和开机打印机&ndash;&gt;-->
            <!--            <view class="flex-between padding-tb-14 common-title" hover-class="hover"-->
            <!--                  @click="onUpdatePrinterStatus(index)">-->
            <!--              <view>-->
            <!--                {{-->
            <!--                  myReplace(lang.operations['updatePrinterStatus'], '{state}', (item.state ? lang.updatePrinterStatus['offState'] : lang.updatePrinterStatus['onState']))-->
            <!--                }}-->
            <!--              </view>-->
            <!--              <view>-->
            <!--                <u-icon :name="arrowIcon" size="18"/>-->
            <!--              </view>-->
            <!--            </view>-->

            <view class="line"/>

            <!-- 打印纸数量设置-->
            <view class="flex-between padding-tb-14 common-title" hover-class="hover" @click="onTonerSettings(index)">
              <view>{{ lang.operations['tonerSettings'] }}</view>
              <view class="flex-center gap-30">
                <view class="flex-center gap-8" :style="{color: formatPaperNumber(item.toner)}">
                  <view class="ltr default-text">{{ item.toner }}</view>
                  <view>{{ otherLang.fix }}</view>
                </view>

                <u-icon :name="arrowIcon" size="18"/>
              </view>
            </view>

            <view class="line"/>

            <!-- 打印纸数量设置-->
            <view class="flex-between padding-tb-14 common-title" hover-class="hover" @click="onPaperSettings(index)">
              <view>{{ lang.operations['paperSettings'] }}</view>
              <view class="flex-center gap-30">
                <!-- a3-->
                <view v-if="getCanPaper(item.paper_types_supported, 'A3')" class="ltr default-text"
                      :style="{color: formatPaperNumber(item.remaining_a3)}">
                  {{ myReplace(lang.paperSettings['a3'], '{A3Cont}', item.remaining_a3) }}
                </view>

                <view :style="{color: formatPaperNumber(item.remaining_a4)}" class="ltr default-text flex-center">
                  {{ myReplace(lang.paperSettings['a4'], '{A4Cont}', item.remaining_a4) }}
                </view>

                <u-icon :name="arrowIcon" size="18"/>
              </view>
            </view>

            <view class="line"/>

            <!-- 价格设计-->
            <navigator
                :url="`/pages/store/printer/paper_price_setting?printer=${encodeURIComponent(JSON.stringify(item))}`"
                class="flex-between padding-tb-14 common-title" hover-class="hover">
              <view>{{ lang.operations['priceSettings'] }}</view>
              <view>
                <u-icon :name="arrowIcon" size="18"/>
              </view>
            </navigator>

            <view class="line"/>

            <!-- 打印二维码-->
            <navigator
                :url="`/pages/store/printer/print_qr_code?printer=${encodeURIComponent(JSON.stringify(item))}`"
                class="flex-between padding-tb-14 common-title" hover-class="hover" style="padding-bottom: 0">
              <view>{{ lang.operations['printQRCode'] }}</view>
              <view>
                <u-icon :name="arrowIcon" size="18"/>
              </view>
            </navigator>
          </view>
          <view style="height: 40rpx"/>
        </view>
        <view style="height: 100rpx"/>
      </view>

      <view v-if="printerList.length <= 0" class="center" style="height: 60vh;">
        <u-empty
            mode="data"
            :width="240"
            :hidden="240"
            :textSize="22"
            :text="lang.emptyPrinter"
            icon="http://cdn.uviewui.com/uview/empty/data.png"
        />
      </view>

      <!--  添加打印机信息弹窗 -->
      <confirm-popup
          :show="addPrinterShow" :title="lang.clearTask['title']"
          @update:show="addPrinterShow = false" @confirm="onPrinterInfoConfirm"
      >
        <u-form :model="deviceInfo" labelPosition="left" ref="uForm" v-if="addPrinterShow">
          <view class="flex-between">
            <view class="column">
              <u-form-item :label="lang.deviceInfo['deviceId']" :labelWidth="80" prop="deviceInfo.device_id">
                <u-input v-model="deviceInfo.device_id" :placeholder="lang.deviceInfo['deviceIdPlaceholder']"
                         border="none" disabledColor="#fff"/>
              </u-form-item>

              <u-form-item :label="lang.deviceInfo['devicePassword']" :labelWidth="80"
                           prop="deviceInfo.device_password">
                <u-input v-model="deviceInfo.device_password"
                         :placeholder="lang.deviceInfo['devicePasswordPlaceholder']" border="none"
                         disabledColor="#fff"/>
              </u-form-item>
            </view>
          </view>
        </u-form>
      </confirm-popup>

      <!-- 修改打印机信息弹窗 -->
      <confirm-popup
          :show="updatePrinterInfo" :title="lang.updateInfo['title']"
          @update:show="updatePrinterInfo = false" @confirm="onPrinterInfoConfirm"
      >
        <u-form :model="printerInfo" labelPosition="left" ref="uForm">
          <u-form-item :label="lang.updateInfo['name']" prop="printerInfo.name" borderBottom :labelWidth="100">
            <input v-if="updatePrinterInfo" border="none" :placeholder="lang.updateInfo['printerName']"
                   v-model="printerInfo.name"/>
          </u-form-item>

          <view class="flex-between">
            <view class="column">
              <u-form-item :label="lang.updateInfo['longitude']" :labelWidth="80" prop="printerInfo.longitude">
                <u-input v-model="printerInfo.longitude" :placeholder="lang.updateInfo['clickIcon']"
                         border="none" disabled disabledColor="#fff"/>
              </u-form-item>

              <u-form-item :label="lang.updateInfo['latitude']" :labelWidth="80" prop="printerInfo.longitude">
                <u-input v-model="printerInfo.latitude" :placeholder="lang.updateInfo['clickIcon']" border="none"
                         disabled disabledColor="#fff"/>
              </u-form-item>
            </view>
            <view class="padding-20 bg-white" @click="getPrinterAddress">
              <u-icon name="map-fill" size="22"
                      :color="printerInfo.longitude && printerInfo.latitude ? '#1073FF' : '#999999'"/>
            </view>
          </view>

          <!-- 打印机支持纸类型-->
          <u-form-item prop="printerInfo.paper_types_supported">
            <view class="flex-between">
              <view class="default-text flex-1">{{ lang.updateInfo['paperType'] }}</view>
              <u-checkbox-group v-model="printerInfo.paper_types_supported" placement="row" @change="checkboxChange">
                <u-checkbox
                    :customStyle="{marginLeft: '10px', gap: '6px'}"
                    v-for="(item, index) in selectedPaperTypes" :key="index" :label="item.name" :name="item.name">
                </u-checkbox>
              </u-checkbox-group>
            </view>
          </u-form-item>

          <!-- 支持颜色-->
          <u-form-item prop="printerInfo.supports_color">
            <view class="flex-between">
              <view class="default-text flex-1">{{ lang.updateInfo['color'] }}</view>
              <view class="flex-1">
                <u-radio-group v-model="printerInfo.supports_color" placement="row">
                  <u-radio
                      :customStyle="{marginLeft: '10px', gap: '6px'}"
                      v-for="(item,index) in selectedColor" :key="index" :label="lang.updateInfo[item.name]"
                      :name="item.value"/>
                </u-radio-group>
              </view>
            </view>
          </u-form-item>

          <!-- 支持双面打印-->
          <u-form-item prop="printerInfo.paper_types_supported">
            <view class="flex-between">
              <view class="default-text flex-1">{{ lang.updateInfo['doubleSide'] }}</view>
              <view class="flex-1">
                <u-radio-group v-model="printerInfo.supports_double_side" placement="row">
                  <u-radio
                      :customStyle="{marginLeft: '10px', gap: '6px'}"
                      v-for="(item,index) in selectedDoubleSide" :key="index" :label="lang.updateInfo[item.name]"
                      :name="item.value"/>
                </u-radio-group>
              </view>
            </view>
          </u-form-item>
        </u-form>
      </confirm-popup>

      <!-- 清空打印任务 -->
      <confirm-popup
          :show="clearPrinterTask" :title="lang.clearTask['title']"
          @update:show="clearPrinterTask = false" @confirm="onClearPrinterTaskConfirm"
      >
        <view class="default-text line-height-one-six">{{ lang.clearTask['content'] }}</view>
      </confirm-popup>

      <!-- 重启设备 -->
      <confirm-popup
          :show="rebootDevice" :title="lang.restart['title']"
          @update:show="rebootDevice = false" @confirm="onRebootDeviceConfirm"
      >
        <view class="center default-text line-height-one-six">{{ lang.restart['content'] }}</view>
      </confirm-popup>

      <!-- 关机打印机和开机 -->
      <confirm-popup
          :show="updatePrinterStatus"
          :title="myReplace(lang.updatePrinterStatus['title'], '{state}', (printerList[currentPrinterIndex].state ? lang.updatePrinterStatus['offState'] : lang.updatePrinterStatus['onState']))"
          @update:show="updatePrinterStatus=false" @confirm="onUpdatePrinterStatusConfirm"
      >
        <view v-if="printerList[currentPrinterIndex].state" class="center default-text line-height-one-six">
          {{ lang.updatePrinterStatus['offDesc'] }}
        </view>
        <view v-if="!printerList[currentPrinterIndex].state" class="center default-text line-height-one-six">
          {{ lang.updatePrinterStatus['onDesc'] }}
        </view>
      </confirm-popup>

      <!-- 修改打印机墨粉数量弹窗 -->
      <confirm-popup
          :show="tonerSettings" :title="lang.tonerSettings['title']"
          @update:show="tonerSettings = false" @confirm="onTonerConfirm"
      >
        <label for="toner" class="flex-center default-text">{{ lang.tonerSettings['remainingCount'] }}
          <input v-if="tonerSettings" type="number" id="toner" class="ltr paper-input"
                 :placeholder="lang.tonerSettings['tonerCount']" v-model="toner"/>{{ otherLang.fix }}
        </label>
      </confirm-popup>

      <!-- 修改打印纸数量弹窗 -->
      <confirm-popup
          :show="paperSettings" :title="lang.paperSettings['title']"
          @update:show="paperSettings = false" @confirm="onPaperConfirm"
      >
        <label v-if="paperSettings && canA3" for="A3" class="flex-center default-text">
          {{ `A3 ${lang.paperSettings['remainingCount']}` }}
          <input type="number" id="A3" class="ltr paper-input" :placeholder="lang.paperSettings['a3Count']"
                 v-model="remainingA3"/>
          {{ otherLang.fix }}
        </label>

        <label for="A4" class="flex-center default-text">
          {{ `A4 ${lang.paperSettings['remainingCount']}` }}
          <input v-if="paperSettings" type="number" id="A4" class="ltr paper-input"
                 :placeholder="lang.paperSettings['a4Count']" v-model="remainingA4"/>
          {{ otherLang.fix }}
        </label>
      </confirm-popup>

      <!-- 故障提示弹窗 -->
      <popup :show="isNoticeCameIn" @update:show="isNoticeCameIn = false">
        <view class="column gap-40">
          <view class="center head-title">{{ lang.errorNotice['title'] }}</view>
          <view class="center default-text">
            {{ lang.errorNotice[noticeType === 'paper' ? 'paper' : (noticeType === 'toner' ? 'toner' : 'offline')] }}
          </view>
        </view>
      </popup>
    </view>
  </view>
</template>

<script lang="ts">
import Vue from 'vue'
import tips from "@/utils/tips";
import Popup from "@/components/popup/popup.vue";
import NavBar from "@/components/nav-bar/nav-bar.vue";
import {getCanPaper, myReplace} from "@/utils/utils";
import {
  getStoreSettings, updatePaperRemaining, updatePrinterInfo, updateTonerRemaining
} from "@/services/store/storeSettings";
import {clearTheTasks, getMachineStatus, rebootDevice} from "@/services/liank";
import {PageData, PrinterItem} from "@/types/store/printer-list";
import {PaperType} from "@/types/mutations";
import ConfirmPopup from "@/components/confirmPopup/confirmPopup.vue";

export default Vue.extend({
  name: "printer_list",
  components: {ConfirmPopup, Popup, NavBar},
  data(): PageData {
    return {
      testShowPopup: false,
      machineOnline: 0,
      printerList: [] as PrinterItem[],
      currentPrinterIndex: 0, // 选定的打印机下标

      addPrinterShow: false, // 添加打印机弹窗
      deviceInfo: {
        device_id: null,
        device_password: null
      },

      updatePrinterInfo: false, // 更新打印机信息弹窗
      printerInfo: {
        name: '',
        latitude: null,
        longitude: null,
        paper_types_supported: [] as PaperType[],
        supports_color: null,
        supports_double_side: null
      },
      selectedPaperTypes: [{name: 'A4',}, {name: 'A3',}],
      selectedColor: [{name: 'support', value: 1}, {name: 'notSupport', value: 0}],
      selectedDoubleSide: [{name: 'support', value: 1}, {name: 'notSupport', value: 0}],

      clearPrinterTask: false, // 清空打印任务弹窗
      rebootDevice: false, // 重启设备弹窗
      updatePrinterStatus: false, // 关闭打印机

      tonerSettings: false, // 设置打印机墨粉弹窗
      toner: 100,

      paperSettings: false, // 打印纸设置弹窗
      remainingA4: null,
      remainingA3: null,
      canA3: false,

      printQRCode: false, // 打印二维码

      noticeType: null,
      isNoticeCameIn: false,
    }
  },
  computed: {
    lang() {
      return this.$t('storePages.printerList')
    },
  },
  onLoad(query?: AnyObject) {
    // 服务通知来的信息进入
    if (query.template_type) {
      this.noticeType = query.template_type
      this.isNoticeCameIn = true
      setTimeout(() => {
        this.isNoticeCameIn = false
      }, 6000)
    }
    console.log(query)
    this.getStorePrinterList()
  },
  methods: {
    checkboxChange(n) {
      console.log('change', n);
    },
    myReplace,
    getCanPaper,
    // 获取店铺打印机列表
    async getStorePrinterList() {
      const {code, data, msg} = await getStoreSettings()
      if (code === 200) {
        // console.log("data -=-=", data)
        // data[0].state = 1
        // console.log("data =-=-", data)
        this.printerList = data
        this.printerList.forEach((printer: any, index: number) => {
          const {device_id, device_password} = printer.machine
          this.getMachineStatusData(device_id, device_password, index)
        })
      } else {
        tips.toast(msg)
      }
    },
    // 获取打印机状态
    async getMachineStatusData(deviceId: string, devicePassword: string, index: number) {
      const res = await getMachineStatus(deviceId, devicePassword)
      if (res.code === 200) {
        uni.hideLoading()
        this.$set(this.printerList[index], 'online', res.data.info.online)
        uni.hideLoading()
      }
    },

    // 修改打印机信息
    onUpdatePrinterInfo(index: number) {
      const printer = this.printerList[index]
      this.currentPrinterIndex = index
      this.printerInfo = {...printer, printer_id: printer.id}
      this.updatePrinterInfo = true
    },
    // 获取当前位置
    getPrinterAddress() {
      uni.chooseLocation({
        success: (res) => {
          const {longitude, latitude} = res
          this.printerInfo = {...this.printerInfo, longitude, latitude}
        }
      })
    },
    onConfirm() {
      console.log('onConfirm')
    },
    // 修改打印机信息 确定
    async onPrinterInfoConfirm() {
      console.log(this.printerInfo)

      return
      const {printerInfo, currentPrinterIndex, printerList} = this;
      console.log(this.printerInfo)
      const updatePrinterRes = await updatePrinterInfo(printerInfo)
      tips.toast(updatePrinterRes.msg)
      this.printerList[currentPrinterIndex] = {...printerList[currentPrinterIndex], ...printerInfo}
      this.updatePrinterInfo = false
    },

    // 清空打印任务弹窗 显示
    onClearPrinterTask(index: number) {
      this.currentPrinterIndex = index
      this.clearPrinterTask = true
    },
    // 清空打印任务弹窗 确定
    onClearPrinterTaskConfirm() {
      const {port, machine: {device_password, device_id}} = this.printerList[this.currentPrinterIndex];
      clearTheTasks(device_id, device_password, port)
      this.clearPrinterTask = false
    },

    // 重启设备
    onRebootDevice(index: number) {
      this.currentPrinterIndex = index
      this.rebootDevice = true
    },
    // 重启设备弹窗 确定
    async onRebootDeviceConfirm() {
      const {device_id, device_password} = this.printerList[this.currentPrinterIndex].machine
      const rebootRes = await rebootDevice(device_id, device_password)
      if (rebootRes.code === 200) {
        console.log(rebootRes)
      }
      this.rebootDevice = false
    },

    // 关机打印机和开机
    onUpdatePrinterStatus(index: number) {
      this.currentPrinterIndex = index
      this.updatePrinterStatus = true
    },
    // 重启设备弹窗 确定
    async onUpdatePrinterStatusConfirm() {
      this.printerList[this.currentPrinterIndex].state = !this.printerList[this.currentPrinterIndex].state
      this.updatePrinterStatus = false
      console.log('onUpdatePrinterStatusConfirm')
    },

    // 打印墨粉设置弹窗 显示
    onTonerSettings(index: number) {
      this.currentPrinterIndex = index
      this.toner = this.printerList[index].toner
      this.tonerSettings = true
    },
    // 修改打印纸数量弹窗 确定
    async onTonerConfirm() {
      const {toner, printerList, currentPrinterIndex} = this
      const {data, code, msg} = await updateTonerRemaining(printerList[currentPrinterIndex].id, toner)
      if (code === 200) {
        this.printerList[currentPrinterIndex].toner = toner
        tips.toast(msg)
        this.tonerSettings = false
      }
    },

    // 打印纸设置弹窗 显示
    onPaperSettings(index: number) {
      const {paper_types_supported, remaining_a4, remaining_a3} = this.printerList[index]
      console.log("paper_types_supported", paper_types_supported)
      this.canA3 = getCanPaper(paper_types_supported, 'A3')
      this.currentPrinterIndex = index
      this.remainingA4 = remaining_a4
      this.remainingA3 = remaining_a3
      this.paperSettings = true
    },
    // 修改打印纸数量弹窗 确定
    async onPaperConfirm() {
      const {canA3, remainingA4, remainingA3, printerList, currentPrinterIndex} = this
      const res = await updatePaperRemaining(printerList[currentPrinterIndex].id, remainingA4, remainingA3)
      if (res.code === 200) {
        if (!canA3) {
          this.printerList[currentPrinterIndex].remaining_a4 = remainingA4
        } else if (canA3) {
          this.printerList[currentPrinterIndex].remaining_a4 = remainingA4
          this.printerList[currentPrinterIndex].remaining_a3 = remainingA3
        }
        tips.toast('修改打印纸数量成功')
        this.paperSettings = false
      }
    },
    // 根据打印纸数量返回颜色
    formatPaperNumber(num: number): string {
      if (num <= 30) return '#ff1616'
      if (num <= 60) return '#FF7D00'
      return '#3c9cff'
    },
    onBack() {
      if (this.noticeType) {
        uni.switchTab({url: '/pages/index/index'})
      }
    }
  }
})
</script>
<style scoped lang="scss">
.image-box {
  position: relative;

  .image {
    background: none;
    width: 120rpx;
    height: 120rpx;
  }
}

.paper-input {
  margin: auto 20rpx;
  width: 50%;
  text-align: center;
  height: 80rpx;
  background: #f5f5f5;
  border: 1rpx solid #e0e0e0;
  border-radius: 16rpx;
  padding: 0 24rpx;
  font-size: 32rpx;

  &.price-input:focus {
    border-color: #007AFF;
    background: #fff;
  }
}

.popup-box .paper-prompt-box {
  width: 86%;
  padding: 54rpx;
  color: #00000099;
  background: white;
  display: inline-block;
  vertical-align: middle;
}

.state-label {
  padding: 8rpx 12rpx;
  border-radius: 12rpx;
  background: white;
  color: #1073FF;
  border: 1rpx solid #1073FF;
}

.state-label-offline {
  color: #F25050;
  background: #FFEDED;
  border: 1rpx solid #FFEDED;
}

.add-printer {
  display: inline-block;
  background-color: $uni-color-primary;
  color: white;
}
</style>